﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ueEngine.Biz.Inf.LogicEntity;
using ueEngine.Framework.Exception;
using ueEngine.Framework.Common;
using ueEngine.Biz.Inf.Entities.DBSupport;
using ueEngine.Framework.Caching;

namespace ueEngine.Biz.Core.AppService.Member
{
    public class FirmService
    {
        private string Agent = string.Empty;
        public FirmService(string userName)
        {
            this.Agent = userName;
        }
        /// <summary>
        /// 快速生成一个代理人，和一个其所代理的企业
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="companyName"></param>
        /// <param name="password"></param>
        /// <param name="phone"></param>
        /// <param name="location"></param>
        /// <returns>-1:用户名已存在，0：注册失败 1：注册成功</returns>
        public CorporationModel Register(MemberModel model)
        {
            var item = new UserService(Agent).Register(model.Password, model.Password, true, model.QQ);
            if (item != null)
            {
                var corporation = CreateCorporation(model.CorporationInfo.CompanyName, string.Empty, model.CorporationInfo.Location, model.CorporationInfo.Phone, model.CorporationInfo.EMail);
                if (corporation != null)
                {
                    corporation.AgentInfo = item;
                    return corporation;
                }
            }           
            return null;
        }
        /// <summary>
        /// 为代理人添加一个新的商家信息
        /// </summary>
        /// <param name="companyName">公司名</param>
        /// <param name="about">关于公司</param>
        /// <param name="location">公司地址</param>
        /// <param name="phone">联系电话</param>
        /// <param name="email">联系email</param>
        /// <returns></returns>
        public CorporationModel CreateCorporation(string companyName, string about, string location, string phone, string email)
        {
            try
            {
                var item = new CorporationModel()
                {
                    CompanyName = companyName,
                    About = about,
                    Location = location,
                    Phone = phone,
                    Agent = this.Agent,
                    EMail = email,
                    CertificationLevel = CertificationLevel.Normal
                    //Identification = false
                };
                if (item.PostAdd() != null)
                {
                    return item;
                }
                return null;
            }
            catch(Exception e)
            {
                return null;
            }
        }
        public CorporationModel UpdateCorporation(CorporationModel corporationModel)
        {
            var dbModel = corporationModel.PostModify();
            if (dbModel != null)
            {
                return dbModel;
            }
            return null;
        }
        ///// <summary>
        ///// 提交送审材料
        ///// </summary>
        ///// <param name="sheet"></param>
        ///// <returns></returns>
        //public CertificationModel Examine(CertificationModel sheet)
        //{
        //    //var context = new CorporationContext(username);
        //    //var corporation = context.Entry().Corporation;
        //    var corporation = new CorporationModel().Element(c => c.Agent == Agent); 
        //    //如果有过发送送审材料的经历
        //    if (corporation.CertificationId > 0)
        //    {
        //        try
        //        {
        //            //如果确实存在以往材料。并且该材料表面未审核通过
        //            var data = new CertificationModel().Element(c => c.Id == corporation.CertificationId);
        //            if (data != null && !data.Certified)
        //            {
        //                data.CertificationType = CertificationType.Company;
        //                data.DeliverWay = DeliverWay.Online;
        //                data.IsClose = false;
        //                data.PostDate = DateTime.Now;
        //                data.Support = data.Support.Concat(sheet.Support).ToList();
        //                if (data.PostModify() != null)
        //                {
        //                    return data;
        //                }
        //                return null;
        //            }
        //            return data;
        //        }
        //        catch (Exception e) 
        //        {
        //            LogHelper.Write(CommonLogger.Zone, LogLevel.Error, e);
        //        }
        //    }
        //    sheet.ExcaminDate = DateTime.Now;
        //    //没有发送过送审材料,且本次投递成功
        //    //var certification = Inverter(sheet);
        //    if (sheet.PostAdd() != null)
        //    {
        //        corporation.CertificationId = sheet.Id;
        //        if (new FirmService(Agent).UpdateCorporation(corporation) != null)
        //        {
        //            return sheet;
        //        }
        //        return null;
        //    }
        //    return null;
        //}
        /// <summary>
        /// 新添加一个代理企业
        /// </summary>
        /// <param name="model"></param>
        /// <param name="createTemplete">以此创建模板</param>
        /// <returns></returns>
        public DepositCompanyModel CreateDepositCompany(DepositCompanyModel model, bool createTemplete)
        {
            model.Templete = createTemplete;
            if (model.PostAdd() != null)
            {
                return model;
            }
            return null;
        }
        public bool DeleteDepositCompany(int id)
        {
            try
            {
                var item = new DepositCompanyModel().Element(c => c.Id == id);
                if (item != null)
                {
                    item.Templete = false;
                    return item.PostModify() != null;
                }
            }
            catch (ContextException exp)
            {
                LogHelper.Write(CommonLogger.Zone, LogLevel.Error, exp);
            }
            return false;
        }
        public ItemListBox<DepositCompanyModel> QueryOfDepositCompany(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = from c in ctx.DepositCompany
                           where c.Agent == Agent && c.Templete
                           orderby c.Id descending
                           select c;
                int itemCount = list.Count();
                var result = new ItemListBox<DepositCompanyModel>(
                    list.Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new DepositCompanyModel()
                    {
                        Agent = c.Agent,
                        CompanyBusiness = (Business)c.CompanyBusiness,
                        CompanyDetail = c.CompanyDetail,
                        CompanyDimensions = (CompanyDimensions)c.CompanyDimensions,
                        CompanyName = c.CompanyName,
                        CompanyType = (CompanyType)c.CompanyType,
                        Id = c.Id,
                        PostDate = c.PostDate
                    })
                    .ToList()
                    ).BuildPage(itemCount, page, pageSize);
                return result;
            }
        }
        /// <summary>
        /// 更新代理公司信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="companyName"></param>
        /// <param name="companyDetail"></param>
        /// <returns></returns>
        public DepositCompanyModel UpdateDepositCompany(int id, string companyName, string companyDetail)
        {
            try
            {
                var item = new DepositCompanyModel().Element(c => c.Id == id);
                item.CompanyName = companyName;
                item.CompanyDetail = companyDetail;
                if (item.PostModify() != null)
                {
                    return item;
                }
            }
            catch (ContextException exp)
            {
                LogHelper.Write(CommonLogger.Zone, LogLevel.Error, exp);
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="loadAgent">是否加载代理人信息</param>
        /// <returns></returns>
        public CorporationModel GetCorporation(bool loadAgent=false)
        {
            CorporationModel item = null;
            if (!String.IsNullOrEmpty(Agent))
            {
                item = ueCache.GetCache<CorporationModel>("GetCorporation:" + Agent);
                if (item == null)
                {
                    var corp = new CorporationModel().Element(c => c.Agent == Agent);
                    item = ueCache.Add<CorporationModel>("GetCorporation:" + Agent, corp, CacheExpireStrategy.Sliding, new TimeSpan(0, 30, 0));
                }
                if (item != null && loadAgent)
                {
                    item.AgentInfo = new UserService(Agent).GetUser();
                }
                return item;
            }
            return null;
        }
        //public void RemoveCacheOfCorporation()
        //{
        //    if (!String.IsNullOrEmpty(Agent))
        //    {
        //        ueCache.RemoveCache("GetCorporation:" + Agent);
        //    }
        //}

        public DepositCompanyModel GetDepositCompany(int id)
        {
            return new DepositCompanyModel().Element(c => c.Id == id);
        }

        //public CertificationModel LoadCertificationInfo(int certificationId)
        //{
        //    return new CertificationModel().Element(c => c.Id == certificationId);
        //}
    }
}
